package com.gjintel.sdk.util;

import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import com.gjintel.framework.log.model.LogInfo;
import com.gjintel.framework.log.service.ILogInfoService;
import com.gjintel.framework.register.model.RegisterUser;
import com.gjintel.framework.user.model.User;

public class LoginInterceptor implements HandlerInterceptor {
	
	@Autowired
	private ILogInfoService logInfoService;
   //在dispatcherServelt 处理后执行
	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub
		
	}
	//在请求处理的方法执行之后执行
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object arg2, ModelAndView arg3)
			throws Exception {
		LogInfo loginLog = new LogInfo();
		HttpSession session =request.getSession();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		User user = (User) session.getAttribute("loginUser");
		RegisterUser rUser=(RegisterUser) session.getAttribute("registerUser");
		if(rUser!=null){			
			loginLog.setOpTime(new Date());
			loginLog.setLogContent("用户"+rUser.getName()+"在"+sdf.format(loginLog.getOpTime())+"时登录");
			loginLog.setOperName(rUser.getName());
			loginLog.setOpEntity("UserLoginSysController1");
			loginLog.setOpType("Login");
			loginLog.setOper(rUser.getId());
			loginLog.setOpId(rUser.getId());
			this.logInfoService.saveOrUpdate(loginLog);		
		}else if(user !=null){
			loginLog.setOpTime(new Date());
			loginLog.setLogContent("用户"+user.getName()+"在"+sdf.format(loginLog.getOpTime())+"时登录");
			loginLog.setOperName(user.getName());
			loginLog.setOpType("Login");
			loginLog.setOpEntity("UserLoginSysController1");
			if(user.getRegisterId() !=null){
				loginLog.setOper(user.getRegisterId());
			}else{
				loginLog.setOper(user.getId());
			}
			loginLog.setOpId(user.getId());
			this.logInfoService.saveOrUpdate(loginLog);		
		}

	}
	//在请求之前处理
	@Override
	public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
		// TODO Auto-generated method stub
		return true;
	}

}
